<?php

namespace frontend\modules\Api\controllers;

use common\event\TallyEvent;
use common\models\TallyFuture;
use common\models\TallyRecord;
use common\services\TallyArapService;
use common\services\TallyFutureServices;
use common\services\TallyPmService;
use common\services\TallyRecordService;
use common\services\TallyService;
use Yii;
use yii\base\DynamicModel;
use yii\base\ExitException;
use yii\base\InvalidConfigException;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

class TallyFutureController extends ApiController
{


    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }


    /**
     * 重载初始化方案
     */
    public function init()
    {
        parent::init();
        // 注册监听事件
        $this->on(TallyEvent::RECORD_LOG_EVENT,['common\models\Tally','recordLog']);
    }


    /**
     * @throws ExitException
     * @throws InvalidConfigException
     */
    public function actionAddLog(){
        $postData =  Yii::$app->getRequest()->post();
        $this->preventBrush('TallyFutureAddLog',1);
        $form = DynamicModel::validateData([
            'tally_id'      => Yii::$app->getRequest()->post('tally_id'), //账本id
            'category_id'   => $postData['category_id'] ?: 0,//分类
            'arap_id'       => $postData['arap_id'] ?: 0,// 应收应付ID
            'future_id'       => $postData['future_id'] ?: 0,// 应收应付ID
            'account_id'    => $postData['account_id'] ?: 0, //账户
            'account_dst_id'  => $postData['account_dst_id'] ?: 0, //目标账户
            'amount'        => Yii::$app->getRequest()->post('amount'), // 金额
            'project_id'    => $postData['project_id'] ?: 0, // 项目
            'store_id'      => $postData['store_id'] ?: 0, // 商家
            'member_id'     => $postData['member_id'] ?: 0, // 成员
            'tally_time'    => Yii::$app->getRequest()->post('tally_time'), // 账单时间
            'is_gua'    => Yii::$app->getRequest()->post('is_gua',0), // 账单时间
            'is_yushou'    => Yii::$app->getRequest()->post('is_yushou',0), // 账单时间
            'uid'   => $this->_user['id'],
            'type'  => Yii::$app->getRequest()->post('type',10),
            'memo'  => Yii::$app->getRequest()->post('memo',''),
            'material_json'  => Yii::$app->getRequest()->post('material_json',''),
            'attachment'  => Yii::$app->getRequest()->post('attachment',''),//附件 多个逗号分隔
            'state' => 0, // 默认状态
            'is_refund'=>Yii::$app->getRequest()->post('is_refund',0)
        ],[
            [['tally_id','account_id','amount','tally_time','type'], 'required'],
            ['type', 'in', 'range' => [TallyRecord::TYPE_IN, TallyRecord::TYPE_OUT, TallyRecord::TYPE_TRANS]],
            ['memo', 'trim'],
        ]);

        //涉及预收====>=新增冲销即可
            $result = TallyFutureServices::calRelationAmount($form->future_id,ArrayHelper::toArray($form),$form);
            if(!$result){
                return self::failureResponse(500,'新增失败.'.TallyArapService::getError());
            }else{
                return self::successResponse(['id'=>$result]);
            }
    }

    /**
     * 获取应收应付款项列表
     * @throws
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $uid = TallyPmService::getRoleUid($this->_user['id'],$tallyId);

        // 默认取出所有状态
        $list = TallyFutureServices::getList($condition,$uid);
        $retData['data'] = [];
        $retData['pageInfo'] = [];
        // 遍历拼装附件数据
        foreach ($list['data'] as $lv) {
            $tmpData = $lv->toArray();
            $tmpData['attachment']  = $lv->attachment;
            $tmpData['type_txt']    = '预收/付';
            $tmpData['is_yushou']    = 1;
            $tmpData['state_txt']  = TallyFuture::getStatusTxt($lv['state']);
            $monthAmount = TallyRecordService::getSumAmountFuture($condition,$lv->id);
            $tmpData['now_price'] = bcsub($monthAmount,0,2);
            $tmpData['all_price'] = bcsub($lv->amount,$lv->amount_remain,2);
            $retData['data'][] = $tmpData;
        }
        $retData['pageInfo'] = $list['pageInfo'];
        return self::successResponse($retData);
    }


    /**
     * @throws \Throwable
     * @throws ExitException
     */
    public function actionDel(){
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'冲销Id不能为空');
        }
        try{
            $result = TallyFutureServices::delete([
                'id'    => $id
            ]);
            if($result){
                return self::successResponse();
            }else{
                return self::failureResponse(500,'删除失败.'.TallyService::getError());
            }
        }catch (\Exception $e) {
            return self::failureResponse(500,'删除失败.'.$e->getMessage());

        }
    }


    /**
     * @throws ExitException
     */
    public function actionLookDetails(){
        $id = Yii::$app->getRequest()->get('id');
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $list  = TallyFutureServices::details($id,$tallyId);
        $retData = [];
        foreach ($list as $lv) {
            $tmpData = $lv->toArray();
            $tmpData['attachment']  = $lv->attachment;
            $tmpData['type_txt']    = '预收/付款';
            $tmpData['state_txt']  = TallyRecord::getStatusTxt($lv['state']);
            $retData[] = $tmpData;
        }
        return self::successResponse($retData);
    }


    /**
     * 某一时间段应付内债务统计 这是总计 总的应收付数据
     * @throws ExitException
     */
    public function actionCount()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        if(Yii::$app->request->isPost){
            $tallyId = Yii::$app->getRequest()->post('tally_id');
        }else{
            $tallyId = Yii::$app->getRequest()->get('tally_id');
        }
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $uid = TallyPmService::getRoleUid($this->_user['id'],$tallyId);

        $retData  = TallyFutureServices::countFuture($condition,$uid);
        return self::successResponse($retData);
    }





    /**
     * 一段时间内的应收付统计，包括以下数据：
     * 1、该时间段新增加的应收付记录：应收额、应付额 通过查询arap表获得
     * 2、该时间段内核销的应收付记录：已收额、已付额 通过查询record表获得
     * @throws \yii\base\ExitException
     */
    public function actionCountPeriod()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $uid = TallyPmService::getRoleUid($this->_user['id'],$tallyId);

        $retData  = TallyFutureServices::countArapPeriod($condition,$uid);
        return self::successResponse($retData);
    }


}